package com.wwc.sc.controller;

import com.wwc.sc.entities.Payment;
import com.wwc.sc.entities.result.CommonResult;
import com.wwc.sc.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author WWC
 */
@RestController
@Slf4j
@RequestMapping(value = "/payment")
public class PaymentController {

    @Resource
    private PaymentService paymentService;

    /**
     * 获取服务端口
     */
    @Value("${server.port}")
    private String serverPort;

    /**
     *服务发现
     */
    @Resource
    private DiscoveryClient discoveryClient;


    @PostMapping(value = "/create")
    @ResponseBody
    public CommonResult create(@RequestBody Payment payment) {
        int result = paymentService.create(payment);
        log.info("成功插入 --------------------->" +result);
        if (result > 0) {
            return new CommonResult(200,"payment新增成功！端口："+serverPort,result);
        }else {
            return new CommonResult(444,"payment新增失败！",null);
        }
    }

    @GetMapping (value = "/getPaymentById/{id}")
    @ResponseBody
    public CommonResult getPaymentById(@PathVariable("id") Long id) {
        Payment payment = paymentService.getPaymentById(id);
        log.info("获取数据 --------------------->" +payment);
        if (payment != null) {
            return new CommonResult(200,"payment查询成功！端口："+serverPort,payment);
        }else {
            return new CommonResult(444,"payment查询失败,没有该记录！", null);
        }
    }

    @GetMapping (value = "/discovery")
    @ResponseBody
    public Object discovery() {
        for (String service : discoveryClient.getServices()) {
            log.info("service-->"+service);
        }
        List<ServiceInstance> instanceList = discoveryClient.getInstances("SPRING-CLOUD-PROVIDER-PAYMENT-SERVICE");
        for (ServiceInstance instance : instanceList) {
            log.info(instance.getServiceId()+"\t"+instance.getInstanceId()+"\t"+instance.getHost()+"\t"+instance.getPort()+"\t"+instance.getUri());
        }
        return this.discoveryClient;
    }

    @GetMapping(value = "/loadBalanced")
    public String getPaymentLoadBalanced() {
        return serverPort;
    }

    @GetMapping(value = "/feign/timeout")
    public String paymentFeignTimeOut()
    {
        System.out.println("*****paymentFeignTimeOut from port: "+serverPort);
        //暂停几秒钟线程
        try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); }
        return serverPort;
    }

}
